package com.hwy.utils;

import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 请求工具类
 */
public class HttpClientUtil {
    /**
     * 模拟浏览器进行get请求返回响应体的流
     *
     * @param url 图片地址
     * @return 图片输入流
     */
    public static InputStream getResponseInputStreamByGet(String url) {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // Get请求
        HttpGet httpGet = new HttpGet(url);
        // 设置请求头
        httpGet.setHeader("Accept", "image/jpeg");
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        // 发送请求并获取相应内容
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            return response.getEntity().getContent();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 模拟浏览器进行get请求返回html内容
     *
     * @param url 页面地址
     * @return html内容
     */
    public static String getHtmlContentByGet(String url) {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 构造Get请求
        HttpGet httpGet = new HttpGet(url);
        // 设置请求头
        httpGet.setHeader("Accept", "text/html");
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        try {
            // 发送请求并获取响应内容
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 获取流中的字节信息
            byte[] bytes = EntityUtils.toByteArray(response.getEntity());
            // 判断内容编码
            CharsetDetector charsetDetector = new CharsetDetector();
            charsetDetector.setText(bytes);
            CharsetMatch match = charsetDetector.detect();
            String matchName = match.getName();
            System.out.println("响应的编码格式为:" + matchName);
            return new String(bytes, matchName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
